using AutoMapper;
using ErrorCode;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RabbitTraceability.Api.Applications.Command;
using RabbitTraceability.Api.Dtos.Request;
using RabbitTraceability.Api.Dtos.Response;
using System.Threading.Tasks;

namespace RabbitTraceability.Api.Controllers
{
    /// <summary>
    /// 养殖信息控制器
    /// </summary>
    [ApiController]
    [Route("[controller]/[action]")]
    [Authorize]
    public class BreedingController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly IMapper _mapper;
        private readonly ILogger<BreedingController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public BreedingController(
            IMediator mediator,
            IMapper mapper,
            ILogger<BreedingController> logger)
        {
            _mediator = mediator;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 保存养殖信息（添加或修改）
        /// </summary>
        /// <remarks>
        /// 如果请求中包含养殖编号(BreedingId)，则执行修改操作；
        /// 如果请求中不包含养殖编号，则执行添加操作。
        /// </remarks>
        /// <param name="request">养殖信息请求</param>
        /// <returns>养殖信息编号</returns>
        [HttpPost]
        public async Task<ApiResult<string>> SaveBreedingInfo([FromBody] SaveBreedingInfoRequestDto request)
        {
            _logger.LogInformation("接收到保存养殖信息请求，批次：{ProductionBatch}", request.ProductionBatch);
            
            // 将DTO映射为命令
            var command = _mapper.Map<SaveBreedingInfoCommand>(request);
            
            // 发送命令并获取结果
            var breedingId = await _mediator.Send(command);
            
            // 返回结果
            return ApiResult<string>.SuccessWithData(breedingId);
        }

        /// <summary>
        /// 根据生产批次获取养殖信息
        /// </summary>
        /// <param name="productionBatch">生产批次</param>
        /// <returns>养殖信息</returns>
        [HttpGet("{productionBatch}")]
        public async Task<ApiResult<BreedingInfoResponseDto>> GetBreedingInfoByBatch(string productionBatch)
        {
            _logger.LogInformation("接收到查询养殖信息请求，批次：{ProductionBatch}", productionBatch);
            
            // 创建查询命令
            var command = new QueryBreedingInfoCommand(productionBatch);
            
            try
            {
                // 发送命令并获取结果
                var breedingInfo = await _mediator.Send(command);
                
                // 返回结果
                return ApiResult<BreedingInfoResponseDto>.SuccessWithData(breedingInfo, "查询成功");
            }
            catch (ApiException ex)
            {
                _logger.LogWarning("查询养殖信息失败：{Message}", ex.Message);
                return ApiResult<BreedingInfoResponseDto>.Error(ex.Code, ex.Message);
            }
        }
    }
} 